package resources

import (
	"os"
	"sync"

	"github.com/rs/zerolog/log"

	"gopkg.in/yaml.v3"
)

type YamlConfig struct {
	Port        int          `yaml:"port"`
	LogPath     string       `yaml:"log_path"`
	Mysql       MysqlConfig  `yaml:"mysql"`
	Redis       RedisConfig  `yaml:"redis"`
	Ip2RegionDb string       `yaml:"ip2region_db"`
	Oss         OssConfig    `yaml:"oss"`
	Wechat      WechatConfig `yaml:"wechat"`
}

type MysqlConfig struct {
	Host         string `yaml:"host"`
	Port         int    `yaml:"port"`
	User         string `yaml:"user"`
	Password     string `yaml:"password"`
	Database     string `yaml:"database"`
	MaxIdleConns int    `yaml:"max_idle_conns"`
	MaxOpenConns int    `yaml:"max_open_conns"`
	MaxLifeTime  int    `yaml:"max_life_time"` // 秒
	MaxIdleTime  int    `yaml:"max_idle_time"` // 秒
}

type RedisConfig struct {
	Host           string `yaml:"host"`
	FrequencyHost  string `yaml:"frequency_host"`
	Port           int    `yaml:"port"`
	Password       string `yaml:"password"`
	PoolSize       int    `yaml:"pool_size"`
	MaxActiveConns int    `yaml:"max_active_conns"`
	MaxIdleConns   int    `yaml:"max_idle_conns"`
	DB             int    `yaml:"db"`
	QuantityDB     int    `yaml:"quantity_db"`
	FrequencyDB    int    `yaml:"frequency_db"`
	CrowdDB        int    `yaml:"crowd_db"`
	Timeout        int    `yaml:"timeout"` // 秒
}

type OssConfig struct {
	Region     string `yaml:"region"`
	AccessID   string `yaml:"access_id"`
	AccessKey  string `yaml:"access_key"`
	BucketName string `yaml:"bucket_name"`
}

type WechatConfig struct {
	AppId     string `yaml:"app_id"`
	AppSecret string `yaml:"app_secret"`
}

var yamlConfig *YamlConfig
var yamlOnce sync.Once

func GetYamlConfig() *YamlConfig {
	return getYamlConfigWithFile("")
}

func getYamlConfigWithFile(folder string) *YamlConfig {
	yamlOnce.Do(func() {
		yamlConfig = &YamlConfig{}
		if folder == "" {
			folder = "resources/"
		}
		file := folder + "config.yml"
		unmarshalYaml(file, yamlConfig)
		env := os.Getenv("GO_ENV")
		if env != "" {
			file = folder + "config-" + env + ".yml"
			unmarshalYaml(file, yamlConfig)
		}
	})
	return yamlConfig
}

func unmarshalYaml(filePath string, yamlConfig *YamlConfig) {
	yamlFile, err := os.ReadFile(filePath)
	if err != nil {
		log.Warn().Msgf("Error reading YAML file: %v", err)
	} else {
		err := yaml.Unmarshal(yamlFile, yamlConfig)
		if err != nil {
			log.Error().Msgf("Error unmarshalling YAML file: %v", err)
		}
	}
}
